import 'package:hive/hive.dart';
import 'package:uuid/uuid.dart';
import '../models/scan_result_model.dart';

class ScanResultService {
  final Box<ScanResultModel> _scanResultBox = Hive.box<ScanResultModel>(
    'scan_results',
  );
  final Uuid _uuid = Uuid();

  // 创建扫描结果
  Future<ScanResultModel> createScanResult({
    required String userId,
    required String imageUrl,
    required String result,
    required String description,
  }) async {
    final scanResult = ScanResultModel(
      id: _uuid.v4(),
      userId: userId,
      imageUrl: imageUrl,
      result: result,
      description: description,
      scanDate: DateTime.now(),
    );

    await _scanResultBox.put(scanResult.id, scanResult);
    return scanResult;
  }

  // 获取扫描结果
  ScanResultModel? getScanResultById(String id) {
    return _scanResultBox.get(id);
  }

  // 更新扫描结果
  Future<void> updateScanResult(ScanResultModel scanResult) async {
    await _scanResultBox.put(scanResult.id, scanResult);
  }

  // 删除扫描结果
  Future<void> deleteScanResult(String id) async {
    await _scanResultBox.delete(id);
  }

  // 获取所有扫描结果
  List<ScanResultModel> getAllScanResults() {
    return _scanResultBox.values.toList()
      ..sort((a, b) => b.scanDate.compareTo(a.scanDate)); // 按扫描时间降序排序
  }

  // 获取用户的扫描结果
  List<ScanResultModel> getUserScanResults(String userId) {
    return _scanResultBox.values.where((scan) => scan.userId == userId).toList()
      ..sort((a, b) => b.scanDate.compareTo(a.scanDate));
  }

  // 获取收藏的扫描结果
  List<ScanResultModel> getFavoriteScanResults() {
    return _scanResultBox.values.where((scan) => scan.isFavorite).toList()
      ..sort((a, b) => b.scanDate.compareTo(a.scanDate));
  }

  // 获取用户收藏的扫描结果
  List<ScanResultModel> getUserFavoriteScanResults(String userId) {
    return _scanResultBox.values
        .where((scan) => scan.userId == userId && scan.isFavorite)
        .toList()
      ..sort((a, b) => b.scanDate.compareTo(a.scanDate));
  }

  // 切换收藏状态
  Future<void> toggleFavorite(String id) async {
    final scanResult = getScanResultById(id);
    if (scanResult != null) {
      scanResult.toggleFavorite();
      await updateScanResult(scanResult);
    }
  }

  // 搜索扫描结果
  List<ScanResultModel> searchScanResults(String query) {
    query = query.toLowerCase();
    return _scanResultBox.values
        .where(
          (scan) =>
              scan.result.toLowerCase().contains(query) ||
              scan.description.toLowerCase().contains(query),
        )
        .toList()
      ..sort((a, b) => b.scanDate.compareTo(a.scanDate));
  }

  // 添加样例扫描结果数据（开发测试用）
  Future<void> createSampleScanResults(List<String> userIds) async {
    if (_scanResultBox.isEmpty && userIds.isNotEmpty) {
      // 确保至少有3个用户来创建样例扫描结果
      if (userIds.length >= 3) {
        // 扫描结果1: 珊瑚礁鱼类
        final scanResult1 = await createScanResult(
          userId: userIds[0],
          imageUrl: 'assets/images/knowledge1.png',
          result: 'Coral Reef Fish Species',
          description:
              'This appears to be a tropical fish commonly found in coral reef ecosystems. It belongs to the family Pomacentridae, also known as damselfish. These colorful fish play an important role in maintaining reef health by controlling algae growth.',
        );

        // 设置为收藏
        await toggleFavorite(scanResult1.id);

        // 扫描结果2: 海龟
        await createScanResult(
          userId: userIds[1],
          imageUrl: 'assets/images/knowledge2.png',
          result: 'Green Sea Turtle (Chelonia mydas)',
          description:
              'This is a Green Sea Turtle, an endangered species protected under international law. These magnificent creatures can live up to 80 years and are critical for maintaining seagrass bed health. They migrate long distances between feeding grounds and nesting beaches.',
        );

        // 扫描结果3: 鲸鲨
        final scanResult3 = await createScanResult(
          userId: userIds[2],
          imageUrl: 'assets/images/knowledge3.png',
          result: 'Whale Shark (Rhincodon typus)',
          description:
              'The whale shark is the largest fish species in the world, reaching lengths of up to 40 feet. Despite their size, they are filter feeders that primarily consume plankton. They are currently listed as endangered due to habitat loss and fishing pressure.',
        );

        // 设置为收藏
        await toggleFavorite(scanResult3.id);

        // 扫描结果4: 珊瑚礁
        await createScanResult(
          userId: userIds[0],
          imageUrl: 'assets/images/knowledge4.png',
          result: 'Healthy Coral Reef Ecosystem',
          description:
              'This image shows a diverse and healthy coral reef ecosystem. Coral reefs support approximately 25% of all marine species while covering less than 1% of the ocean floor. They are threatened by climate change, pollution, and destructive fishing practices.',
        );

        // 扫描结果5: 海葵和小丑鱼
        await createScanResult(
          userId: userIds[1],
          imageUrl: 'assets/images/knowledge5.png',
          result: 'Clownfish and Sea Anemone Symbiosis',
          description:
              'This shows the famous symbiotic relationship between clownfish and sea anemones. The clownfish is immune to the anemone\'s stinging tentacles and receives protection, while the anemone benefits from the clownfish\'s aggressive defense against predators and food scraps.',
        );
      }
    }
  }
}
